package com.gtw.modules.wx;

import com.gtw.modules.api.controller.weixinController;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 *
 * @author wuye
 * @date 2018/3/5
 */
public class AdvancedUtil {

    private static Logger log = LoggerFactory.getLogger(AdvancedUtil.class);
    /**
     * 获取网页授权凭证
     *
     * @param appId 公众账号的唯一标识
     * @param appSecret 公众账号的密钥
     * @param code
     * @return WeixinAouth2Token
     */
    public static WeixinOauth2Token getOauth2AccessToken(String appId, String appSecret, String code) {
        WeixinOauth2Token wat = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code";
        requestUrl = requestUrl.replace("APPID", appId);
        requestUrl = requestUrl.replace("SECRET", appSecret);
        requestUrl = requestUrl.replace("CODE", code);
        // 获取网页授权凭证
        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
        if (null != jsonObject) {
            try {
                wat = new WeixinOauth2Token();
                wat.setAccessToken(jsonObject.getString("access_token"));
                wat.setExpiresIn(jsonObject.getInt("expires_in"));
                wat.setRefreshToken(jsonObject.getString("refresh_token"));
                wat.setOpenId(jsonObject.getString("openid"));
                wat.setScope(jsonObject.getString("scope"));
            } catch (Exception e) {
                wat = null;
                int errorCode = jsonObject.getInt("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                log.error("获取网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
            }
        }
        return wat;
    }


    /**
     *
     * @return
     */
    /*public static String getWeixinCgiToken(String accesstoken){

        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;
        requestUrl = requestUrl.replace("APPID", appId);
        requestUrl = requestUrl.replace("SECRET", appSecret);
        // 获取网页授权凭证
        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
        if (null != jsonObject) {
            try {

                accesstoken = jsonObject.getString("access_token");
            } catch (Exception e) {
                accesstoken = null;
                int errorCode = jsonObject.getInt("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                log.error("获取网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
            }
        }
        return accesstoken;
    }*/


//    /**
//     *
//     * @param url
//     * @return
//     */
//    public static JSONObject getWeixinQrcode(String url,String accesstoken){
//        // 拼接请求地址
//        String requestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+accesstoken;
//        String data = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+url+"\"}}}";
//        // 获取网页授权凭证
//        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "POST", data);
//        return jsonObject;
//    }
//
//
//    /**
//     *
//     * @param ticket
//     * @return
//     */
//    public static String getWeixinImg(String ticket){
//        // 拼接请求地址
//        String requestUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket;
//        return requestUrl;
//    }
//
//
//    /**
//     * url地址长地址转短地址
//     * @return
//     */
//    public static String getWeixinShorurl(String longurl,String accesstoken){
//        // 拼接请求地址
//        String requestUrl = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token="+accesstoken;
//        String data = "{\"action\":\"long2short\",\"long_url\":\""+longurl+"\"}";
//        // 获取网页授权凭证
//        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "POST", data);
//        return jsonObject.getString("short_url");
//    }


    /**
     * 通过网页授权获取用户信息
     *
     * @param accessToken 网页授权接口调用凭证
     * @param openId 用户标识
     * @return SNSUserInfo
     */
    @SuppressWarnings( { "deprecation", "unchecked" })
    public static SNSUserInfo getSNSUserInfo(String accessToken, String openId) {
        SNSUserInfo snsUserInfo = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        // 通过网页授权获取用户信息
        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                snsUserInfo = new SNSUserInfo();
                // 用户的标识
                snsUserInfo.setOpenId(jsonObject.getString("openid"));
                // 昵称
                snsUserInfo.setNickname(jsonObject.getString("nickname"));
                // 性别（1是男性，2是女性，0是未知）
                snsUserInfo.setSex(jsonObject.getInt("sex"));
                // 用户所在国家
                snsUserInfo.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                snsUserInfo.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                snsUserInfo.setCity(jsonObject.getString("city"));
                // 用户头像
                snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
                // 用户特权信息
                snsUserInfo.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class));
            } catch (Exception e) {
                snsUserInfo = null;
                int errorCode = jsonObject.getInt("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                log.error("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg);
            }
        }
        return snsUserInfo;
    }

    /**
     * 根据openid获取用户信息
     * @param accessToken
     * @param openId
     * @return
     */
    public static SNSUserInfo getWxUserInfo(String accessToken, String openId){
        Logger logger = LoggerFactory.getLogger(AdvancedUtil.class);
        SNSUserInfo snsUserInfo = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        // 通过网页授权获取用户信息
        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                snsUserInfo = new SNSUserInfo();
                // 用户的标识
                logger.error(jsonObject.getString("openid"));
                snsUserInfo.setOpenId(jsonObject.getString("openid"));
                // 昵称
                logger.error(jsonObject.getString("nickname"));
                snsUserInfo.setNickname(jsonObject.getString("nickname"));
                // 性别（1是男性，2是女性，0是未知）
                logger.error(jsonObject.getString("sex"));
                snsUserInfo.setSex(jsonObject.getInt("sex"));
                // 用户所在国家
                logger.error(jsonObject.getString("country"));
                snsUserInfo.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                logger.error(jsonObject.getString("province"));
                snsUserInfo.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                logger.error(jsonObject.getString("city"));
                snsUserInfo.setCity(jsonObject.getString("city"));
                // 用户头像
                logger.error(jsonObject.getString("headimgurl"));
                snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
            } catch (Exception e) {
                snsUserInfo = null;
                int errorCode = jsonObject.getInt("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                log.error("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg);
            }
        }
        return snsUserInfo;
    }
}
